package com.hcloud.baselib.http

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


object HttpClient {


    private var retrofit: Retrofit? = null

    private val okClient = OkHttpClient.Builder()
        .connectTimeout(1, TimeUnit.MINUTES)
        .readTimeout(1, TimeUnit.MINUTES)
        .writeTimeout(1, TimeUnit.MINUTES)
        .addInterceptor(HttpLoggingInterceptor())
        .build()


    fun initRetrofit(baseUrl: String): HttpClient {
        retrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return this
    }

    fun <T> getService(serviceClass: Class<T>): T {
        if (retrofit == null) {
            throw UninitializedPropertyAccessException("Retrofit must init!!!")
        } else {
            return retrofit!!.create(serviceClass)
        }
    }
}